package com.ifdom.reflection;

import org.springframework.util.ReflectionUtils;

import java.lang.annotation.Annotation;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

/**
 * @Author ifredom
 * @Date 2022/6/29
 * @ClassName Reflection1
 * @Version 1.0.0
 * @Description 描述
 **/
public class Reflection1 {
    public static void main(String[] args) throws ClassNotFoundException, InstantiationException, IllegalAccessException, NoSuchFieldException, NoSuchMethodException, InvocationTargetException {
        Class<?> clazz = Class.forName("com.ifdom.reflection.Song");

        Constructor<?>[] constructors = clazz.getConstructors();

        // 无参构造函数
        for (Constructor<?> constructor : constructors) {
            if (constructor.getParameterCount() == 0) {
                Object instance = constructor.newInstance();
            }
        }

        // 有参构造函数
        Object instance = clazz.getDeclaredConstructor().newInstance();
        Object instance1 = clazz.getDeclaredConstructor(String.class).newInstance("一个参数");
        Object instance2 = clazz.getDeclaredConstructor(new Class<?>[]{String.class, String.class}).newInstance("参数一", "参数二");

        // 获取属性上的修饰符类型
        Field titleField = clazz.getDeclaredField("title");
        int modifiers = titleField.getModifiers();
        System.out.println(modifiers);

        // 获取所有属性字段名
        Field[] fields = clazz.getDeclaredFields();
        for (Field field : fields) {
            if ("author".equals(field.getName())) {
                field.setAccessible(true);
                field.set(instance2, "设置属性");
            }
        }
        System.out.println(instance2);

        // 获取属性字段名
        Field authorField = clazz.getDeclaredField("author");
        String fieldName = authorField.getName();

        System.out.println(fieldName);


        // 获取方法上的修饰符类型
        Method testMethod = clazz.getMethod("test");
        int modifiers2 = testMethod.getModifiers();

        // 获取方法的注解
        Annotation testMethodAnnotation1 = testMethod.getAnnotation(DemoAnnotation.class);
        System.out.println(testMethodAnnotation1);

        // 获取类的注解
        Annotation testMethodAnnotation2 = clazz.getAnnotation(DemoAnnotation.class);
        System.out.println(testMethodAnnotation2);


    }

}
